<?php
namespace lemon\repository;

use Yii;

class FileHelper{
	
	public static function storeFile($files, $folder= ''){
		$result=[];
		if(empty($folder)){
			$folder= 'uploads';
		}
		$dir_path = '/'.$folder.'/'.date("Y/m/");
		$physical_path = Yii::$app->params['FILE_PHYSICAL_PATH'];
		$domain_http = Yii::$app->params['FILE_HTTP_PATH'];
		$real_path = $physical_path.$dir_path;
		
		if (!file_exists($real_path)){
			mkdir($real_path, 0777, true);
		}
		
		foreach ($files as $key => $file)
		{
			try{
				$extension = $file->extension;
				$file_name = Utility::createRandom(15);
				$doc = $file_name.'.'.$extension;
				$save_result = $file ->saveAs($real_path. $doc);
				if(!$save_result){
					throw new \Exception("文件保存失败");
				}
				
				$result[]=['result'=>1, 'name'=>$file->name, 'file'=>$dir_path.$doc, 'http'=>$domain_http];
			}
			catch(\Exception $ex){
				$result[]=['result'=>0, 'name'=>$file->name, 'msg'=>$ex->getMessage()];
			}
			
		}
		return $result;
	}
}